import {action, makeAutoObservable, observable} from "mobx";
import {BIND_CHECK, GET_USER_INFO} from "../api/APIURLDefine";
import {AxioInstance} from "../api/AxiosHelper";

interface UserInfo {
    name: string;
    nickname: string;
    avatarUrl: string;
    phone: string;
    city: string;
    country: string;
}

interface StudentInfo {

}

export default class UserStore {
    @observable accessToken = "";

    @observable userInfo: any = null;

    @observable studentInfo: StudentInfo = null

    /*专家账号*/
    @observable testAccount: string = null;
    /*专家密码*/
    @observable testPwd: string = null;

    @action setTestAccount = (account: string) => {
        this.testAccount = account;
    }
    @action setTestPwd = (pwd: string) => {
        this.testPwd = pwd;
    }


    constructor() {
        makeAutoObservable(this);
        this.setToken();
    }

    setToken() {
        var token = window.localStorage.getItem("APP_ACCESSTOKEN");
        if (token) {
            this.setAccessToken(token);
        }
    }

    @action
    async setAccessToken(accessToken: string) {
        this.accessToken = accessToken;
        if (accessToken) {
            var userInfo = await AxioInstance.get(GET_USER_INFO).catch(() => undefined);
            if (userInfo) {
                window.localStorage.setItem("APP_ACCESSTOKEN", accessToken);
                this.setUserInfo(userInfo);
            }
        } else {
            window.localStorage.removeItem("APP_ACCESSTOKEN");
            this.setUserInfo(null);
        }
    }
    @action async ReloadUserInfo(){
        if (this.accessToken) {
            var userInfo = await AxioInstance.get(GET_USER_INFO).catch(() => undefined);
            if (userInfo) {
                this.setUserInfo(userInfo);
            }
        } else {
            window.localStorage.removeItem("APP_ACCESSTOKEN");
            this.setUserInfo(null);
        }
    }

    @action setUserInfo(userInfo: any) {
        this.userInfo = userInfo;
        this.checkBind();
    }

    @action setStudentInfo(studentInfo: any) {
        this.studentInfo = studentInfo;
    }

    @observable bind = false;
    //绑定信息
    @observable bindMessage: any = null;

    @action setBindMessage(msg: any) {
        this.bindMessage = msg;
    }

    @action checkBind() {
        if (this.userInfo) {
            AxioInstance.get(`${BIND_CHECK}`).then((data: any) => {
                this.setBindMessage(data);
                if (data.state === 1) {
                    // console.log("身份认证成功")
                    this.bind = true;
                } else {
                    throw new Error("未进行身份绑定");
                }
            }).catch((e) => {
                // console.error("未进行身份绑定");
                this.bind = false;
            });
        }
    }

    /*  @action setUserId(userId:Number){
         this.userId=userId
     } */
}
